<?php

// 引入thinkphp的http库和image库
import("ORG.Net.Http");
import("ORG.Util.Image");


// 消息处理类
class MessageAction extends Action {
    /* 保存消息
     * 
     * 
     * 
     */
	public function save($p){
		// 初始化模型
		$Message = D("Message");
		
		// json参数转换为数组
		$param = Output::instance()->toObject($p);

		//print_r($param);
		// 先插入素材表
// 		$data['msgType']     = $param->msgType;
// 		$data['toUserName']  = $param->toUserName;
// 		$data['fromUserName']= $param->fromUserName;
// 		$data['content']     = $param->content;
// 		$data['picUrl']      = $param->picUrl;
// 		$data['locationX']   = $param->locationX;
// 		$data['locationY']   = $param->locationY;
// 		$data['scale']       = $param->scale;
// 		$data['label']       = $param->label;
// 		$data['title']       = $param->title;
// 		$data['description'] = $param->description;
// 		$data['url']         = $param->url;
// 		$data['event']       = $param->event;
// 		$data['eventKey']    = $param->eventKey;

		// 验证参数合法性,合法则添加
		$result = $Message->create($param);
		if(!$result){
			exit($Message->getError());
		}	
		$msgid = $Message->add();
		if($msgid==0){
			return;
		}
		
		$this->show('save','utf-8');
    }
    
    // 回复消息
    public function reply(){
    	$this->show('reply','utf-8');
    }
    
    // 获取列表 $openid暂时不传
    public function index($cid,$startDate='',$endDate='',
    		$order="createTime",$orderBy="desc",$start=0,$limit=25) {
    	$retVal = Session::init();
 		if (!$retVal) {
    		Output::instance()->resultCode(code_access_denied);
    		return;
    	}
    	if(!isset($cid) ){
// 	    	Log::write("customerId:".Session::$user["customerId"]);
    		$cid = Session::$user["customerId"];
    	}
    	if($cid == 0){
    		$prefix = C('ORIGINAL_DB_PREFIX');
    	}else{
    		$prefix = C('ORIGINAL_DB_PREFIX').$cid.'_';
    	}
    	
    	// 初始化模型
    	$Message = new Model();
    	// 设置查询条件
    	
    	if ($startDate) {
    		$sql = 'select a.*,b.id as uid,b.profileUrl,b.fullName,c.customerId from wx_customer_user c, '
    		.$prefix.'message as a left outer join '
    		.$prefix.'user as b on a.fromUserName=b.userName '
    		.'where (a.createTime BETWEEN "'.$startDate.'" and "'.$endDate.'") '
    		.'and ( a.msgType <> "event" ) '
    		.'and ( (a.msgMark <> "reply") OR (a.msgMark is null) ) '
    		.'and c.customerId='.$cid
			.' ORDER BY a.'.$order.' '.$orderBy.' LIMIT '.$start.','.$limit
    		;
    	}else{
    		$sql = 'select a.*,b.id as uid,b.profileUrl,b.fullName,c.customerId from wx_customer_user c, '
    		.$prefix.'message as a left outer join '
    		.$prefix.'user as b on a.fromUserName=b.userName '
    		.'where ( a.msgType <> "event" ) '
    		.'and ( (a.msgMark <> "reply") OR (a.msgMark is null) ) '
    		.'and c.customerId='.$cid
    		.' ORDER BY a.'.$order.' '.$orderBy.' LIMIT '.$start.','.$limit
    		;
    	}
    	
    	$arr = $Message->query($sql);
    	if ($arr) {
    		$MessageCount= new Model();
    		// 设置查询条件
    		if ($startDate) {
    			//SELECT * FROM `wx_2_message` WHERE (  (`createTime` BETWEEN '2013-06-26 00:00:00' AND '2013-07-01 23:59:59' ) ) AND ( `msgType` <> 'event' ) AND ( (`msgMark` <> 'reply') OR (`msgMark` is null) )
    			$countSql = 'select count(*)  as tp_count from '
    			.$prefix.'message where ( msgType <> "event" ) '
    			.'and ( (msgMark<> "reply") or (msgMark is null) )'
    			.'and (createTime between "'.$startDate.'" and "'.$endDate.'") LIMIT 1 '
    			;
    		}else{
    			$countSql = 'select count(*) as tp_count from '.$prefix.'message where ( msgType <> "event" ) AND ( (msgMark<> "reply") OR (msgMark is null) ) LIMIT 1 ';
    		}
    		 
	    	//处理图片对应的url
	    	MessageAction::cachefile($arr);
	    	//echo $Message->getLastSql();
	    	$count = $MessageCount->query($countSql);
// 	    	Log::write('all MessageCount is :'.$count[0][tp_count]);
// 	    	Log::write('all msg index sql:'.$MessageCount->getLastSql());
		    Output::instance()->objArray($arr, $count[0][tp_count]);
    	}
    	else {
    		Output::instance()->resultCode(code_success,"未找到消息");
    	}
    }
    
    // 获取$fromUserName 相应所有消息列表 
    public function getListByFromUserName($fromUserName,$startDate='',$cid=null,$endDate='',
    		$order="id",$orderBy="desc",$start=0,$limit=25) {
    	$retVal = Session::init();
 		if (!$retVal) {
    		Output::instance()->resultCode(code_access_denied);
    		return;
    	}
    	if(!isset($cid)){
//     		Log::write("customerId:".Session::$user["customerId"]);
    		$cid = Session::$user["customerId"];
    	}
    	//$cid = Session::$user["customerId"];
    	if($cid == 0){
    		$prefix = C('ORIGINAL_DB_PREFIX');
    	}else{
    		$prefix = C('ORIGINAL_DB_PREFIX').$cid.'_';
    	}
    	
    	// 初始化模型
    	$Message = new Model();
    	/*
    	 * 	SELECT a.*,b.id as uid,b.profileUrl,b.fullName,c.fullName as CFullName,c.profileUrl as CProfileUrl
			FROM `wx_2_message` as a
			left outer join wx_2_user as b ON a.fromUserName=b.userName 
			left outer join wx_customer_user c on a.customerId = c.customerId 
			WHERE ( a.msgType <> 'event' ) 
			AND ((a.toUserName = 'fromUser')  OR  (a.fromUserName = 'fromUser')) 
			ORDER BY a.id desc LIMIT 0,25  
			
							
							
			
    	 */

		if ($startDate) {
			$sql ='select *,cus.fullName as CFullName,cus.profileUrl as CProfileUrl from '
				.$prefix.'message as mes,wx_customer_user as cus,'
				.$prefix.'user_weixin_info as info  WHERE cus.customerId='.$cid.' and cus.agent<>"service" and cus.agent<>"agent"  and  (mes.fromUserName=info.openid OR mes.toUserName=info.openid) '
				.'and ( (mes.toUserName = "'.$fromUserName.'") OR (mes.fromUserName = "'.$fromUserName.'") ) and mes.msgType <> "event"'
				.'GROUP BY mes.id ORDER BY mes.'.$order.' '.$orderBy.' LIMIT '.$start.','.$limit;
			/*
                $sql = 'select e.headimgurl,e.nickname,a.*,b.id as uid,b.profileUrl,b.fullName,c.fullName as CFullName,c.profileUrl as CProfileUrl,c.customerId from wx_customer_user c, '
                .$prefix.'message as a,  '
                .$prefix.'user_weixin_info as e,   '
                .$prefix.'user as b where (a.fromUserName=b.userName or a.toUserName = b.userName) and b.`userName` = e.`openid` '
                //.'left outer join wx_customer_user c on a.customerId = c.customerId '
                .'and (a.createTime BETWEEN "'.$startDate.'" and "'.$endDate.'") '
                .'and ( a.msgType <> "event" ) '
                .'and ( (a.toUserName = "'.$fromUserName.'") OR (a.fromUserName = "'.$fromUserName.'") ) '
                .'and c.customerId='.$cid." and c.agent<>'service'"
                .' ORDER BY a.'.$order.' '.$orderBy.' LIMIT '.$start.','.$limit
                ; */
		}else{
			$sql ='select *,cus.fullName as CFullName,cus.profileUrl as CProfileUrl from '
				.$prefix.'message as mes,wx_customer_user as cus,'
				.$prefix.'user_weixin_info as info  WHERE cus.customerId='.$cid.' and cus.agent<>"service" and cus.agent<>"agent"  and  (mes.fromUserName=info.openid OR mes.toUserName=info.openid) '
				.'and ( (mes.toUserName = "'.$fromUserName.'") OR (mes.fromUserName = "'.$fromUserName.'") ) and mes.msgType <> "event"'
				.'GROUP BY mes.id ORDER BY mes.'.$order.' '.$orderBy.' LIMIT '.$start.','.$limit;
			/* 
			echo $sql;
    		$sql = 'select e.headimgurl,e.nickname,a.*,b.id as uid,b.profileUrl,b.fullName,c.fullName as CFullName,c.profileUrl as CProfileUrl,c.customerId from wx_customer_user c, '
    		.$prefix.'message as a,  '
    		.$prefix.'user_weixin_info as e,   ' 
    		.$prefix.'user as b where (a.fromUserName=b.userName or a.toUserName = b.userName) and b.`userName` = e.`openid` '    		
    		//.'left outer join wx_customer_user c on a.customerId = c.customerId '    		
    		.'and ( a.msgType <> "event" ) '
    		.'and ( (a.toUserName = "'.$fromUserName.'") OR (a.fromUserName = "'.$fromUserName.'") ) '
    		.'and c.customerId='.$cid." and c.agent<>'service'"
    		.' ORDER BY a.'.$order.' '.$orderBy.' LIMIT '.$start.','.$limit
    		; */
		}
    	//echo $sql;
    	$arr = $Message->query($sql);
			//log::write('userMessage'.$Message->getLastSql());
    	//echo $Message->getLastSql();
//     	Log::write($Message->getLastSql());

    	$MessageCount= new Model();
    	// 设置查询条件
    	if ($startDate) {
			$countSql ='select count(mes.id) as count from '
    		.$prefix.'message as mes,wx_customer_user as cus '
    		.'WHERE cus.customerId='.$cid.' and cus.agent="business" '
    		.'and ( (mes.toUserName = "'.$fromUserName.'") OR (mes.fromUserName = "'.$fromUserName.'") ) and mes.msgType <> "event"';
			
    		/*//SELECT * FROM `wx_2_message` WHERE (  (`createTime` BETWEEN '2013-06-26 00:00:00' AND '2013-07-01 23:59:59' ) ) AND ( `msgType` <> 'event' ) AND ( (`msgMark` <> 'reply') OR (`msgMark` is null) )
    		$countSql = 'select count(*) as tp_count from '
    		.$prefix.'message,wx_customer_user c where ( msgType <> "event" ) '
    		.'and ( (toUserName = "'.$fromUserName.'") OR (fromUserName = "'.$fromUserName.'") ) '.'and c.customerId='.$cid." and c.agent<>'service' "
    		.'and (createTime between "'.$startDate.'" and "'.$endDate.'") '
    		;*/
    	}else{
    		$countSql ='select count(mes.id) as count from '
    		.$prefix.'message as mes,wx_customer_user as cus'
    		.' WHERE cus.customerId='.$cid.' and cus.agent="business" and'
    		.' ( (mes.toUserName = "'.$fromUserName.'") OR (mes.fromUserName = "'.$fromUserName.'") ) and mes.msgType <> "event"';
			
    		/*$countSql = 'select count(*) as tp_count from '
    		.$prefix.'message,wx_customer_user c where ( msgType <> "event" ) '
    		.'and ( (toUserName = "'.$fromUserName.'") OR (fromUserName = "'.$fromUserName.'") ) '.'and c.customerId='.$cid." and c.agent<>'service' "
    		;*/
    	}
    	if ($arr) {
			$count = $MessageCount->query($countSql);
		//log::write('countsql'.$countSql);
			//log::write('count'.$count);
    		//处理图片对应的url
    		MessageAction::cachefile($arr);
    		Output::instance()->objArray($arr, $count[0]['count']);
    	}
    	else {
    		Output::instance()->resultCode(code_success,"未找到消息");
    	}
    }
    
    // 获取$fromUserName 相应所有消息列表 
    public function getListByUserName($fromUserName,$startDate='',$endDate='',
    		$order="id",$orderBy="desc",$start=0,$limit=25) {
    	
    	$retVal = Session::init();
 		if (!$retVal) {
    		Output::instance()->resultCode(code_access_denied);
    		return;
    	}
    	
    	$MessageModel = M("message");
    	
    	$cid = Session::$user["customerId"];
    	
    	if ($startDate) {
    		$condition['createTime'] = array('between',$startDate,$endDate);
    		$condition['msg.msgType'] = array('neq',"event");
    		$condition['_string'] = ' (msg.toUserName = "'.$fromUserName.'") OR (msg.fromUserName = "'.$fromUserName.'") ';
    		
    		//     		$condition['uuser.customerId'] = array('eq',$cid);
    		$arr = $MessageModel->alias('msg')
//     		->join('LEFT JOIN wx_uni_user as uuser on msg.fromUserName=uuser.fromUserName ')
//     		->join('LEFT JOIN wx_uni_user_info as info on info.uniUserId=uuser.uniUserId ')
    		//     		->join('LEFT JOIN wx_customer_user as cuser  on cuser.customerId= '.$cid)
    		->where($condition)
    		->field("msg.*")
    		//     		->field("msg.*,info.picUrl as uPicUrl,info.fullName as uFullName,cuser.fullName as CFullName,cuser.profileUrl as CProfileUrl,cuser.customerId")
    		->limit("$start, $limit")
    		->order("$order $orderBy")->select();
    		
    	}else{
    		$condition['msg.msgType'] = array('neq',"event");
    		$condition['_string'] = ' (msg.toUserName = "'.$fromUserName.'") OR (msg.fromUserName = "'.$fromUserName.'") ';
//     		$condition['uuser.customerId'] = array('eq',$cid);
    		
    		$arr = $MessageModel->alias('msg')
//     		->join('LEFT JOIN wx_uni_user as uuser on msg.fromUserName=uuser.fromUserName ')
//     		->join('LEFT JOIN wx_uni_user_info as info on info.uniUserId=uuser.uniUserId ')
//     		->join('LEFT JOIN wx_customer_user as cuser  on cuser.customerId= '.$cid)
    		->where($condition)
    		->field("msg.*")
//     		->field("msg.*,info.picUrl as uPicUrl,info.fullName as uFullName,cuser.fullName as CFullName,cuser.profileUrl as CProfileUrl,cuser.customerId")
    		->limit("$start, $limit")
    		->order("$order $orderBy")->select();
    	
    	}
    	
//     	Log::write($MessageModel->getLastSql());

    	if ($arr) {
    		
    		if ($startDate) {
    			
    			$count =$MessageModel->alias('msg')
//     			->join('LEFT JOIN wx_uni_user as uuser on msg.fromUserName=uuser.fromUserName ')
//     			->join('LEFT JOIN wx_uni_user_info as info on info.uniUserId=uuser.uniUserId ')
    			//     		->join('LEFT JOIN wx_customer_user as cuser  on cuser.customerId= '.$cid)
    			->where($condition)
    			->count();
    		}else{
    			$count =$MessageModel->alias('msg')
// 	    		->join('LEFT JOIN wx_uni_user as uuser on msg.fromUserName=uuser.fromUserName ')
// 	    		->join('LEFT JOIN wx_uni_user_info as info on info.uniUserId=uuser.uniUserId ')
	//     		->join('LEFT JOIN wx_customer_user as cuser  on cuser.customerId= '.$cid)
	    		->where($condition)
	    		->count();
    		}
    		
    		
    		//处理图片对应的url
    		MessageAction::cachefile($arr);
    		Output::instance()->objArray($arr, $count);
    	}
    	else {
    		Output::instance()->resultCode(code_success,"未找到消息");
    	}
    }
    
    
    /*
     * 保存图片到本地路径并更改路径的返回地址，如果本地已经存在直接修改路径值
    */
    private function cachefile(&$arr)
    {
    
    	for($i=0;$i<count($arr);$i++)
    	{
//     		Log::write($arr[$i]['picUrl']);
    		//$str=explode('/',$arr[$i]['picurl']) ;
	    		//Log::write($arr[$i]['picUrl']);
	    	if(isset($arr[$i]['picUrl'])){
// 	    		Log::write("picUrl isset:".$arr[$i]['picUrl']);
		    	$arr[$i]['picUrl'] = get_cache_image($arr[$i]['picUrl']);
	    	}
	    	
	    	if(isset($arr[$i]['profileUrl']) && ($arr[$i]['profileUrl']!=DEFAULT_PROFILE_URL)){
// 	    		Log::write("profileUrl isset:".$arr[$i]['profileUrl']);
	    		$arr[$i]['profileUrl'] = get_cache_image($arr[$i]['profileUrl']);
	    	}
	    	if(isset($arr[$i]['CProfileUrl']) && ($arr[$i]['CProfileUrl']!=DEFAULT_PROFILE_URL)){
// 	    		Log::write("CProfileUrl isset:".$arr[$i]['CProfileUrl']);
	    		$arr[$i]['CProfileUrl'] = get_cache_image($arr[$i]['CProfileUrl']);
	    	}
    	}
    }
    
    public function setText($fromUserName, $content) {
    	$retVal = Session::init();
    	if (!$retVal) {
    		Output::instance()->resultCode(code_access_denied);
    		return;
    	}
    	WeixinApi::sendText($fromUserName, $content, true);
    }
}